const axios = require('axios');

// 测试微信手机号登录功能，验证openid检查逻辑
async function testWechatPhoneLoginWithValidation() {
  try {
    // 测试1: 使用有效的手机号和openid登录（用户已存在）
    console.log('Test 1: Login with existing phone number and openid');
    const response1 = await axios.post('http://localhost:3000/api/users/wechat-phone-login', {
      phone_number: '13800138000',
      openid: 'test_openid_12345'
    });
    
    console.log('Login successful:', response1.data);
    
    // 测试2: 尝试使用有效的手机号但无效的openid登录
    console.log('\nTest 2: Try to login with existing phone number but invalid openid');
    try {
      const response2 = await axios.post('http://localhost:3000/api/users/wechat-phone-login', {
        phone_number: '13800138000',
        openid: 'invalid_openid'
      });
      
      console.log('Unexpected success:', response2.data);
    } catch (error) {
      console.log('Expected failure:', error.response ? error.response.data : error.message);
    }
    
    // 测试3: 尝试使用新的手机号和openid创建用户（应该失败）
    console.log('\nTest 3: Try to create new user with phone number and openid (should fail)');
    try {
      const response3 = await axios.post('http://localhost:3000/api/users/wechat-phone-login', {
        phone_number: '13900139000',
        openid: 'test_openid_newuser'
      });
      
      console.log('Unexpected success:', response3.data);
    } catch (error) {
      console.log('Expected failure:', error.response ? error.response.data : error.message);
    }
    
    // 测试4: 不使用openid创建新用户
    console.log('\nTest 4: Create new user without openid');
    try {
      const response4 = await axios.post('http://localhost:3000/api/users/wechat-phone-login', {
        phone_number: '13700137000'
      });
      
      console.log('User created successfully:', response4.data.user);
      
      // 验证用户信息
      if (response4.data.user.nickname && response4.data.user.nickname.includes('User')) {
        console.log('User info correctly set');
      } else {
        console.log('Warning: User info might not be correctly set');
      }
    } catch (error) {
      console.error('Failed to create user:', error.response ? error.response.data : error.message);
    }
    
    console.log('\nAll tests completed');
  } catch (error) {
    console.error('Test failed:', error.response ? error.response.data : error.message);
  }
}

testWechatPhoneLoginWithValidation();
